package com.alm.token.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.RegisterView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.LogUtil;
import com.alm.token.utils.MyOnclickListener;
import com.alm.token.utils.PopupAdapter;
import com.alm.token.utils.Utils;
import com.alm.token.widget.CommonPopupWindow;
import com.alm.token.widget.Countdownbutton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnFocusChange;

import static com.alm.token.ConStant.county;
import static com.alm.token.ConStant.countyID;
import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_CODE_VAULE;
import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_INTO_CODE;
import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_NAME_VAULE;
import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_SUCC_CODE;

public class ChangePhoneActivity extends BaseActivity implements RegisterView<RegisterData>, CommonPopupWindow.ViewInterface {
    @BindView(R.id.edt_inputusername)
    TextView edtInputusername;
    @BindView(R.id.edt_inputpswone)
    EditText edtInputpswone;
    @BindView(R.id.edt_inputphone)
    TextView edtInputphone;
    @BindView(R.id.edt_inputcode)
    EditText edtInputcode;
    @BindView(R.id.tv_getcode)
    Countdownbutton tvGetcode;
    @BindView(R.id.tv_setphonecode)
    TextView tvSetphonecode;
    @BindView(R.id.tv_clickphonecountry)
    TextView tvClickphonecountry;

    @BindView(R.id.edt_inputphone2)
    EditText edtInputphone2;
    @BindView(R.id.edt_inputcode2)
    EditText edtInputcode2;
    @BindView(R.id.tv_getcode2)
    Countdownbutton tvGetcode2;
    @BindView(R.id.tv_setphonecode2)
    TextView tvSetphonecode2;
    @BindView(R.id.tv_clickphonecountry2)
    TextView tvClickphonecountry2;

    @BindView(R.id.tv_pswsubmit)
    TextView tvPswsubmit;
    private String strUserName, strPhone, strCode, strPswone, strPhone2, strCode2;
    private String[] countys = new String[14];

    @Override
    protected MyPreenter initPreenter() {
//        MyApp.mOkHttpClient = null;
//        RetrofitUtil.getInstance().setInstance();

        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_change_phone;
    }

    @Override
    protected void initVariables() {
        for (int i = 0; i < countys.length; i++) {
            countys[i] = getResources().getString(county[i]);
        }
    }

    @Override
    protected void initViews() {

        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item30));
        tvPswsubmit.setOnClickListener(this);
        tvGetcode.setOnClickListener(this);
        tvGetcode2.setOnClickListener(this);
        tvClickphonecountry.setOnClickListener(this);
        tvClickphonecountry2.setOnClickListener(this);
        if (MyApp.getUserData() != null && MyApp.getUserData().getData() != null && MyApp.getUserData().getData().getUser() != null) {
            edtInputusername.setText(MyApp.getUserData().getData().getUser().getLoginname());
            strPhone=MyApp.getUserData().getData().getUser().getPhone();
            edtInputphone.setText(strPhone.length()>6?strPhone.substring(0,3)+"****"+strPhone.substring(strPhone.length()-4,strPhone.length()):strPhone);
        }
    }

    @Override
    protected void loadData() {
    }

    int popFlag = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_clickphonecountry:
                popFlag = 1;
//                showDownPop(tvSetphonecode);
                startActivityForResult(FundArealistActivity.class,INTENT_RESULT_INTO_CODE);
                break;
            case R.id.tv_clickphonecountry2:
//                showPopupMenu2(tvSetphonecode);
                popFlag = 2;
//                showDownPop(tvSetphonecode2);
                startActivityForResult(FundArealistActivity.class,INTENT_RESULT_INTO_CODE);
                break;

            case R.id.tv_pswsubmit:

                if (edtInputpswone.getText().toString().isEmpty()) {
                    showToast(getString(R.string.wallet_hint_pleaseinputpsw));
                    edtInputpswone.setFocusable(true);
                    edtInputpswone.setFocusableInTouchMode(true);
                    edtInputpswone.requestFocus();
                    //显示软键盘
//                     this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
                    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edtInputpswone, 0);
                    break;
                }


                if (edtInputcode.getText().toString().isEmpty()) {
                    showToast(getString(R.string.profile_hint_warn11));
                    edtInputcode.setFocusable(true);
                    edtInputcode.setFocusableInTouchMode(true);
                    edtInputcode.requestFocus();
                    //显示软键盘
//                     this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
                    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edtInputcode, 0);
                    break;
                }

                if (edtInputphone2.getText().toString().isEmpty()) {
                    showToast(getString(R.string.profile_hint_warn19));
                    edtInputphone2.setFocusable(true);
                    edtInputphone2.setFocusableInTouchMode(true);
                    edtInputphone2.requestFocus();
                    //显示软键盘
//                     this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
                    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edtInputphone2, 0);
                    break;
                }
                if (edtInputcode2.getText().toString().isEmpty()) {
                    showToast(getString(R.string.profile_hint_warn11));
                    edtInputcode2.setFocusable(true);
                    edtInputcode2.setFocusableInTouchMode(true);
                    edtInputcode2.requestFocus();
                    //显示软键盘
//                     this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
                    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edtInputcode2, 0);
                    break;
                }

                strUserName = edtInputusername.getText().toString();
                strCode = edtInputcode.getText().toString();
                strPhone2 = edtInputphone2.getText().toString();
                strCode2 = edtInputcode2.getText().toString();
                strPswone = edtInputpswone.getText().toString();

//                if (!Utils.verifyUserName(strPswone)) {
//                    showToast(getString(R.string.profile_hint_warn22));
//                    break;
//                }
                if (strPswone.length() < 4 || strPswone.length() > 20) {
                    showToast(getString(R.string.profile_hint_warn33));
                    break;
                }
//                if (!(strPswone.substring(0)
//                        + strPswone.substring(strPswone.length() - 1))
//                        .matches("[0-9A-Za-z]*")) {
//                    showToast(getString(R.string.profile_hint_warn4));
//                    break;
//                }
//                if (!Utils.verifyUserNameFL(strPswone)) {//[A-Za-z1-9]{2}
//                    showToast(getString(R.string.profile_hint_warn44));
//                    break;
//                }
//                showToast("提交注册 " + "strUserName= " + strUserName + "  strPhone=" + strPhone + " strCode=" + strCode
//                        + " strPswone=" + strPswone + " strPswonece=" + strPswone + " strinviteCode=" + strinviteCode);

//                MyApp.Token="";
//                if(preenter==null){
//                    AppClient.mRetrofit=null;
//                    preenter=new MyPreenter(this);
//                }
                preenter.changePhoneData(strPhone,strCode,strPhone2,strCode2,strPswone);
//                preenter.getmodfixMyPwdData("+" + Integer.parseInt(tvSetphonecode.getText().toString()) + strPhone, strPswone, strCode, strUserName);
//                preenter.getmodfixMyPwdData(strPhone, strPswone, strCode, strUserName);
                break;

            case R.id.tv_getcode:
                if (!Utils.isPhoneNumberValid("+" + Integer.parseInt(tvSetphonecode.getText().toString()) + strPhone,
                        Integer.parseInt(tvSetphonecode.getText().toString()) + "")) {
                    showToast(getString(R.string.profile_hint_warn7));
                    break;
                }
//                showToast("点击获取验证码");
//                MyApp.Token="";
//                if(preenter==null){
//                    AppClient.mRetrofit=null;
//                    preenter=new MyPreenter(this);
//                }
                tvGetcode.start();
                LogUtil.d("9999验证码1" + "+" + Integer.parseInt(tvSetphonecode.getText().toString()) + strPhone);
                preenter.getSmsCodeData(strPhone, MyPreenter.check, Integer.parseInt(tvSetphonecode.getText().toString()) + "");
//                preenter.getSmsCodeData(strPhone);
                break;
            case R.id.tv_getcode2:
                strPhone2 = edtInputphone2.getText().toString();
                if (strPhone2.isEmpty()) {
                    showToast(getString(R.string.profile_hint_warn19));
                    edtInputphone2.setFocusable(true);
                    edtInputphone2.setFocusableInTouchMode(true);
                    edtInputphone2.requestFocus();
                    //显示软键盘
//                     this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
                    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edtInputphone2, 0);
                    break;
                } else if (!Utils.isPhoneNumberValid("+" + Integer.parseInt(tvSetphonecode2.getText().toString()) + strPhone2,
                        Integer.parseInt(tvSetphonecode2.getText().toString()) + "")) {

                    showToast(getString(R.string.profile_hint_warn7));
                    edtInputphone2.setFocusable(true);
                    edtInputphone2.setFocusableInTouchMode(true);
                    edtInputphone2.requestFocus();
                    //显示软键盘
//                     this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
                    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edtInputphone2, 0);
                    break;
                }
                tvGetcode2.start();
                LogUtil.d("9999验证码2" + "+" + Integer.parseInt(tvSetphonecode2.getText().toString()) + strPhone2);
                preenter.getSmsCodeData(strPhone2, MyPreenter.check, Integer.parseInt(tvSetphonecode2.getText().toString()) + "");
//                preenter.getSmsCodeData(strPhone);
                break;
            default:
                break;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==INTENT_RESULT_INTO_CODE&&resultCode==INTENT_RESULT_SUCC_CODE&&data!=null){
            String name=data.getStringExtra(INTENT_RESULT_NAME_VAULE);
            String code=data.getStringExtra(INTENT_RESULT_CODE_VAULE);
            LogUtil.e("name="+name+"  code="+code);
            if (popFlag == 1) {
                tvSetphonecode.setText(code);
                tvClickphonecountry.setText(name);
            } else if (popFlag == 2) {
                tvSetphonecode2.setText(code);
                tvClickphonecountry2.setText(name);
            }
        }
    }

    @OnFocusChange({ R.id.edt_inputcode,
            R.id.edt_inputpswone})
    void onEdiFocusChange(View view, boolean hasFocus) {
        switch (view.getId()) {


            case R.id.edt_inputcode:

                break;
            case R.id.edt_inputpswone:

                break;

        }


    }

    @Override
    public void getData(RegisterData registerData) {
        showToast(registerData.getMsg());
        if (registerData.getStatus() == 0)
            finish();
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        }else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog(getString(R.string.profile_hint_warn17));
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @Override
    public void getCode(RegisterData registerData) {
        if (registerData.getMsg().equalsIgnoreCase(getString(R.string.profile_hint_warn15))) {
            showToast(getString(R.string.profile_hint_warn14));
        } else {
            showToast(registerData.getMsg());
        }
    }

    @Override
    public void getcreateCode(Bitmap bitmap) {

    }

    private CommonPopupWindow popupWindow;

    //向下弹出
    public void showDownPop(View view) {
        if (countrys.size() == 0) {
            for (int i = 0; i < countys.length; i++) {
                countrys.add(countys[i]);
                countryMap.put(countys[i], countyID[i]);
            }
        }
        if (popupWindow != null && popupWindow.isShowing()) return;
        popupWindow = new CommonPopupWindow.Builder(this)
                .setView(R.layout.popup_down)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setAnimationStyle(R.style.AnimDown)
                .setViewOnclickListener(this)
                .setOutsideTouchable(true)
                .create();
        popupWindow.showAsDropDown(view);
        //得到button的左上角坐标
//        int[] positions = new int[2];
//        view.getLocationOnScreen(positions);
//        popupWindow.showAtLocation(findViewById(android.R.id.content), Gravity.NO_GRAVITY, 0, positions[1] + view.getHeight());
    }

    public List<String> countrys = new ArrayList<>();
    public Map<String, String> countryMap = new HashMap<>();

    @Override
    public void getChildView(View view, int layoutResId) {
        //获得PopupWindow布局里的View
        switch (layoutResId) {
            case R.layout.popup_down:
                RecyclerView recycle_view = (RecyclerView) view.findViewById(R.id.recycle_view);
                recycle_view.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//                recycle_view.setLayoutManager(new GridLayoutManager(this, 3));
                PopupAdapter mAdapter = new PopupAdapter(this, countrys);
                recycle_view.setAdapter(mAdapter);
                mAdapter.setOnItemClickListener(new MyOnclickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (popFlag == 1) {
                            tvSetphonecode.setText(countryMap.get(countrys.get(position)));
                            tvClickphonecountry.setText(countrys.get(position));
                        } else if (popFlag == 2) {
                            tvSetphonecode2.setText(countryMap.get(countrys.get(position)));
                            tvClickphonecountry2.setText(countrys.get(position));
                        }

                        if (popupWindow != null) {
                            popupWindow.dismiss();
                        }
                    }
                });
                break;
        }
    }
}
